<template>
  <div
    v-loading="loading"
    element-loading-text="加载中..."
    style="display: flex; flex-direction: column; height: 100%"
  >
    <div class="top_app">
      <div class="top_h">
        <div class="text">
          <template v-if="slaData.id">
            <span class="module_color">编辑SLA</span>
            <HStatus v-if="!slaData?.status">启用</HStatus>
            <HStatus v-else type="info">禁用</HStatus>
          </template>
          <span v-else class="module_color">新建SLA</span>
        </div>
        <div style="display: flex; gap: 5px">
          <HPlainButton @click="onSave">保存</HPlainButton>
          <HButton @click="onCancel">取消</HButton>
        </div>
      </div>
    </div>
    <div class="app-container">
      <div class="app-container-inner">
        <div class="heard_title">基本信息</div>
        <el-form
          ref="ruleFormRef"
          :model="slaData"
          :rules="slaDataRules"
          class="newOut-ruleForm"
          label-width="75"
        >
          <div class="form_content">
            <el-form-item label="SLA名称" prop="name">
              <el-input v-model="slaData.name" clearable placeholder="请输入SLA名称" />
            </el-form-item>
            <el-form-item label="适用模块" prop="moduleIds">
              <el-select
                v-model="slaData.moduleIds"
                :filter-method="changmoduleList"
                clearable
                filterable
                multiple
                collapse-tags
                collapse-tags-tooltip
                placeholder="请选择"
                remote-show-suffix
              >
                <el-option
                  v-for="item in moduleList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="提醒方式" prop="remindMode">
              <el-select
                v-model="slaData.remindMode"
                collapse-tags-tooltip
                filterable
                collapse-tags
                multiple
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in remindModeList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.val"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="SLA状态">
              <el-radio-group v-model="slaData.status">
                <el-radio :value="false">启用</el-radio>
                <el-radio :value="true">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="生效时间" prop="dateType">
              <el-select v-model="slaData.dateType" placeholder="请选择" style="width: 100%">
                <el-option :value="1" label="全天" />
                <el-option :value="2" label="时间范围" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="slaData.dateType === 2" label="时间范围" prop="endTime">
              <div style="display: flex; align-items: center; width: 100%; gap: 5px">
                <el-time-select
                  v-model="slaData.startTime"
                  :max-time="slaData.endTime"
                  class="reservationTime-el-time-select"
                  end="22:00"
                  placeholder="开始时间"
                  size="small"
                  start="06:00"
                  step="1:00"
                />
                <span class="reservationTime-span">~</span>
                <el-time-select
                  v-model="slaData.endTime"
                  :min-time="slaData.startTime"
                  class="reservationTime-el-time-select"
                  end="22:00"
                  placeholder="结束时间"
                  size="small"
                  start="06:00"
                  step="1:00"
                />
              </div>
            </el-form-item>
          </div>
          <el-form-item label="描述">
            <el-input
              v-model="slaData.remark"
              clearable
              placeholder="可输入描述"
              type="textarea"
              maxlength="300"
              show-word-limit
              resize="both"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="app-container" style="height: 100%; padding-top: 0">
      <div class="app-container-inner" style="display: flex; flex-direction: column; flex: 1">
        <div class="heard_title">触发条件</div>
        <div style="flex: 1; position: relative">
          <el-table
            :border="true"
            :data="slaData.slaConditionVos"
            height="100%"
            resizable
            stripe
            style="position: absolute"
          >
            <template #empty>
              <el-empty description="暂无数据" />
            </template>

            <!-- 序号 -->
            <el-table-column fixed label="序号" width="70">
              <template v-slot="scope">
                <span class="order"> {{ scope.$index + 1 }} </span>
                <span class="add_delete">
                  <el-icon class="add" color="#007cff" size="16" @click="addGoodsList">
                    <CirclePlus />
                  </el-icon>
                  <el-icon
                    color="rgba(245, 108, 108, 1)"
                    size="16"
                    @click="detelePro(scope.$index)"
                  >
                    <Delete />
                  </el-icon>
                </span>
              </template>
            </el-table-column>

            <!-- 触发条件 -->
            <el-table-column label="触发条件" show-overflow-tooltip width="170">
              <template v-slot="i">
                <el-select v-model="i.row.type" @change="changeType(i.row.type, i.$index)">
                  <el-option
                    v-for="item in typeList"
                    :key="item.name"
                    :disabled="isStop(item.val)"
                    :label="item.name"
                    :value="item.val"
                  />
                </el-select>
              </template>
            </el-table-column>

            <!-- 节点时效 -->
            <el-table-column label="节点时效" width="240">
              <template #header>
                节点时效
                <el-popover
                  ref="popoverEnabledAll"
                  :width="160"
                  placement="top-start"
                  trigger="click"
                >
                  <h5 style="margin-bottom: 10px">批量开启/关闭</h5>
                  <div style="display: flex; align-items: center; gap: 7px; white-space: nowrap">
                    <el-switch v-model="enabledAll" inline-prompt />
                    <span v-if="enabledAll">开启</span>
                    <span v-else>关闭</span>
                  </div>
                  <p style="font-size: 12px; color: #999">不开启则该节点不生效</p>
                  <div style="display: flex; justify-content: end; margin-top: 10px">
                    <el-button
                      color="#007cff"
                      style="padding: 0 4px; height: 20px"
                      @click="changeEnabledAll"
                      >确定</el-button
                    >
                  </div>
                  <template #reference>
                    <span class="multiple_btn">批量</span>
                  </template>
                </el-popover>
              </template>
              <template v-slot="i">
                <div style="display: flex; align-items: center">
                  <div style="display: flex; align-items: center; gap: 7px; white-space: nowrap">
                    <el-switch v-model="i.row.enabled" inline-prompt />
                    <span v-if="i.row.enabled">开启</span>
                    <span v-else>关闭</span>
                  </div>
                  <el-input
                    v-model="i.row.ageingTime"
                    :disabled="!i.row.enabled"
                    placeholder="时效"
                    style="margin-left: 10px"
                    @input="i.row.ageingTime = i.row.ageingTime.replace(/[^0-9]/g, '')"
                  >
                    <template #append>小时</template>
                  </el-input>
                </div>
              </template>
            </el-table-column>

            <!-- 提醒条件 -->
            <el-table-column label="提醒条件" show-overflow-tooltip width="120">
              <template v-slot="i">
                <div style="display: flex; align-items: center; gap: 7px">
                  <el-switch
                    v-model="i.row.enableBeforeOverTimeRemind"
                    :disabled="!i.row.enabled"
                    inline-prompt
                  />
                  <span :style="{ color: i.row.disabled ? '#333' : '#999' }">超时前</span>
                </div>
                <span style="display: flex; align-items: center; gap: 7px">
                  <el-switch
                    v-model="i.row.enableAfterOverTimeRemind"
                    :disabled="!i.row.enabled"
                    inline-prompt
                  />
                  <span :style="{ color: i.row.disabled ? '#333' : '#999' }">超时后</span>
                </span>
              </template>
            </el-table-column>

            <!-- 提醒事件 -->
            <el-table-column label="提醒时间" show-overflow-tooltip width="220">
              <template v-slot="i">
                <el-input
                  v-if="i.row.enableBeforeOverTimeRemind"
                  v-model="i.row.beforeOverTimeRemindTime"
                  :disabled="!i.row.enabled"
                  placeholder="超时前提醒时间"
                  @input="
                    i.row.beforeOverTimeRemindTime = i.row.beforeOverTimeRemindTime.replace(
                      /[^0-9]/g,
                      '',
                    )
                  "
                >
                  <template #prepend>每 </template>
                  <template #append>小时</template>
                </el-input>
                <br v-if="i.row.enableBeforeOverTimeRemind" />
                <el-input
                  v-if="i.row.enableAfterOverTimeRemind"
                  v-model="i.row.afterOverTimeRemindTime"
                  :disabled="!i.row.enabled"
                  placeholder="超时后提醒时间"
                  style="margin-top: 5px"
                  @input="
                    i.row.afterOverTimeRemindTime = i.row.afterOverTimeRemindTime.replace(
                      /[^0-9]/g,
                      '',
                    )
                  "
                >
                  <template #prepend>每 </template>
                  <template #append>小时</template>
                </el-input>
              </template>
            </el-table-column>

            <!-- 提醒对象类型 -->
            <el-table-column label="提醒对象类型" min-width="120" show-overflow-tooltip>
              <template #default="scope">
                <el-select
                  v-if="scope.row.enableBeforeOverTimeRemind"
                  v-model="scope.row.beforeOverTimeRemindEmpType"
                  :disabled="!scope.row.enabled"
                  multiple
                  placeholder="提醒对象类型"
                  style="width: 100%"
                  collapse-tags-tooltip
                  filterable
                  collapse-tags
                >
                  <el-option
                    v-for="item in OverTimeRemindEmpType"
                    :key="item.name"
                    :disabled="OverTimeRemindEmpTypeScl(scope.row.type, item.val)"
                    :label="item.name"
                    :value="item.val"
                  />
                </el-select>
                <br v-if="scope.row.enableBeforeOverTimeRemind" />
                <el-select
                  v-if="scope.row.enableAfterOverTimeRemind"
                  v-model="scope.row.afterOverTimeRemindEmpType"
                  :disabled="!scope.row.enabled"
                  multiple
                  collapse-tags-tooltip
                  filterable
                  collapse-tags
                  placeholder="提醒对象类型"
                  style="width: 100%; margin-top: 5px"
                >
                  <el-option
                    v-for="item in OverTimeRemindEmpType"
                    :key="item.name"
                    :disabled="OverTimeRemindEmpTypeScl(scope.row.type, item.val)"
                    :label="item.name"
                    :value="item.val"
                  />
                </el-select>
              </template>
            </el-table-column>

            <!-- 提醒对象 -->
            <el-table-column label="提醒对象" min-width="120" show-overflow-tooltip>
              <template #default="scope">
                <el-select
                  v-if="
                    scope.row.enableBeforeOverTimeRemind &&
                    scope.row.beforeOverTimeRemindEmpType.includes('2')
                  "
                  v-model="scope.row.slaBeforeOverTimeRemindEmpIds"
                  :disabled="!scope.row.enabled"
                  multiple
                  collapse-tags-tooltip
                  filterable
                  collapse-tags
                  placeholder="超时前提醒对象"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in scope.row.customersData"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
                <br v-if="scope.row.enableBeforeOverTimeRemind" />
                <el-select
                  v-if="scope.row.enableAfterOverTimeRemind"
                  v-model="scope.row.slaAfterOverTimeRemindEmpIds"
                  :disabled="!scope.row.enabled"
                  collapse-tags-tooltip
                  filterable
                  collapse-tags
                  :style="`margin-top: 5px;width: 100%;opacity: ${
                    scope.row.enableAfterOverTimeRemind &&
                    scope.row.afterOverTimeRemindEmpType.includes('2')
                      ? '1'
                      : '0'
                  };`"
                  multiple
                  placeholder="超时后提醒对象"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in scope.row.customersData"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { onMounted, ref, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import { workModulePageSelect } from '../../../api/order'
  import { getBeforeEditData, SaveSLA } from '../../../api/sla'
  import { empPageSelecct } from '../../../api/organize'
  import { useRoute, useRouter } from 'vue-router'
  import { Delete, CirclePlus } from '@element-plus/icons-vue'
  import _ from 'lodash'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.setting.slaFormSet,
  })

  const TagsViewStore = useTagsViewStore()
  const router = useRouter()
  const route = useRoute()
  const slaData = ref({
    dateType: 1, //生效时间类型：1-全天，2-时间范围,示例值(1)
    endTime: '',
    startTime: '',
    id: null,
    moduleIds: [], //模块ID集合
    name: '',
    remark: '',
    remindMode: ['3'], //	提醒方式：1-系统消息，2-微信，3-短信，支持多选,示例值([ "3" ])
    slaConditionVos: [
      ////	SLA触发条件集合对象
      {
        afterOverTimeRemindEmpType: [],
        afterOverTimeRemindTime: 0, //超时后提醒时间，单位小时
        ageingTime: 1, //时效，单位小时，当ienabled=true时生效
        beforeOverTimeRemindEmpType: [],
        beforeOverTimeRemindTime: 0, //超时前提醒时间，单位小时
        enableAfterOverTimeRemind: false, //是否启用超时后提醒：false-不启用，true-启用
        enableBeforeOverTimeRemind: false, //是否启用超时前提醒：false-不启用，true-启用
        enabled: false, //是否开启节点时效：false-不开启，true-开启
        id: null,
        slaAfterOverTimeRemindEmpIds: [], //超时后提醒指定人员ID对象
        slaBeforeOverTimeRemindEmpIds: [], //超时前提醒指定人员ID对象
        type: null, //触发条件类型
        customersData: [],
      },
    ],
    status: false, //SLA状态：false-启用，true-禁用
  })
  const moduleList: any = ref([])
  const ruleFormRef = ref()
  const StartEenTime = () => {
    return (rule: any, value: string, callback: any) => {
      if (!(slaData.value.endTime && slaData.value.startTime)) {
        callback(new Error('请选择时间范围'))
      } else {
        callback()
      }
    }
  }
  const slaDataRules = ref({
    name: [{ required: true, message: '请输入SLA名称', trigger: ['blur', 'change'] }],
    moduleIds: [{ required: true, message: '适用模块', trigger: ['blur', 'change'] }],
    remindMode: [{ required: true, message: '提醒方式', trigger: ['blur', 'change'] }],
    dateType: [{ required: true, message: '生效时间', trigger: ['blur', 'change'] }],
    endTime: [
      { required: true, message: '时间范围', trigger: ['blur', 'change'] },
      {
        validator: StartEenTime(),
        trigger: 'blur',
      },
    ],
  })

  const remindModeList = ref([
    { name: '系统消息', val: '1' },
    { name: '微信', val: '2' },
    { name: '短信', val: '3' },
  ])
  //超时前、后提醒人员
  const OverTimeRemindEmpType = ref([
    { name: '工单客服', val: '1' },
    { name: '指定人员', val: '2' },
    { name: '服务商负责人', val: '3' },
    { name: '工程师', val: '4' },
  ])
  //触发条件类型
  const typeList = ref([
    { name: '未分配客服', val: 1 },
    { name: '未派单', val: 2 },
    { name: '服务商未接单', val: 3 },
    { name: '工程师未接单', val: 4 },
    { name: '工程师未拨打电话', val: 5 },
    { name: '工程师未预约', val: 6 },
    { name: '工程师未签到', val: 7 },
  ])
  const loading = ref(false)

  //获取工单模块
  const workModulePageSelectList = () => {
    let data = {
      name: valName.value, //SLA名称
      page: 0, //当面页码
      limit: 0, //每页显示数量
    }
    workModulePageSelect(data).then((res) => {
      moduleList.value = res.data.data.rows
    })
  }
  const valName = ref('')
  const changmoduleList = _.throttle((val: string) => {
    valName.value = val
  }, 500)
  watch(valName, () => {
    workModulePageSelectList()
  })
  watch(
    () => slaData.value.dateType,
    (n) => {
      if (n == 1) {
        slaData.value.endTime = ''
        slaData.value.startTime = ''
      }
    },
  )
  onMounted(async () => {
    loading.value = true
    if (route.params.id) {
      await getBeforeEdit(route.params.id)
    }
    workModulePageSelectList()
    slaData.value.slaConditionVos.map((o, index) => {
      getworkTeamPageSelect('', index)
    })
    loading.value = false
  })
  const getBeforeEdit = async (id) => {
    await getBeforeEditData(id).then((res) => {
      if (res) {
        slaData.value = res.data.data.row
      }
    })
  }
  // 触发条件不能重复
  const isStop = (val) => {
    let arr = []
    arr = slaData.value.slaConditionVos.map((o) => {
      return o.type
    })
    return arr.includes(val)
  }
  // 根据触发条件可选人员类型
  const OverTimeRemindEmpTypeScl = (type, val) => {
    switch (type) {
      case 1:
        if (val != '2') {
          return true
        }
        break
      case 2:
        if (val == '3' || val == '4') {
          return true
        }
        break
      case 3:
        if (val == '4') {
          return true
        }
        break
    }
  }
  // 获取客服
  const getworkTeamPageSelect = (val, index) => {
    // 仅当缓存中没有数据时才触发请求
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    empPageSelecct(data).then((res) => {
      if (res.data.success) {
        slaData.value.slaConditionVos[index].customersData = res.data.data.rows
      }
    })
  }
  // 触发条件改变时 人员类型重新选择
  const changeType = (type, index) => {
    slaData.value.slaConditionVos = slaData.value.slaConditionVos.map((o, i) => {
      if (i == index) {
        switch (type) {
          case 1:
            o.beforeOverTimeRemindEmpType = o.beforeOverTimeRemindEmpType.filter((i) => i == '2')
            o.afterOverTimeRemindEmpType = o.afterOverTimeRemindEmpType.filter((i) => i == '2')
            break
          case 2:
            o.beforeOverTimeRemindEmpType = o.beforeOverTimeRemindEmpType.filter(
              (i) => i == '1' || i == '2',
            )
            o.afterOverTimeRemindEmpType = o.afterOverTimeRemindEmpType.filter(
              (i) => i == '1' || i == '2',
            )
            break
          case 3:
            o.beforeOverTimeRemindEmpType = o.beforeOverTimeRemindEmpType.filter((i) => i != '4')
            o.afterOverTimeRemindEmpType = o.afterOverTimeRemindEmpType.filter((i) => i != '4')
            break
        }
      }
      return o
    })
  }
  // 批量开启/关闭
  const enabledAll = ref(false)
  const popoverEnabledAll = ref()
  const changeEnabledAll = () => {
    slaData.value.slaConditionVos = slaData.value.slaConditionVos.map((o) => {
      o.enabled = enabledAll.value
      return o
    })
    popoverEnabledAll.value.hide()
  }
  //添加
  const addGoodsList = () => {
    slaData.value.slaConditionVos.push({
      afterOverTimeRemindEmpType: [], //超时后提醒人员类型：1-工单客服，2-指定人员，3-服务商负责人，4-工程师,示例值([ "2" ])
      afterOverTimeRemindTime: null, //超时后提醒时间，单位小时
      ageingTime: 1, //时效，单位小时，当ienabled=true时生效
      beforeOverTimeRemindEmpType: [], //超时前提醒人员类型：1-工单客服，2-指定人员，3-服务商负责人，4-工程师,示例值([ "2" ])
      beforeOverTimeRemindTime: null, //超时前提醒时间，单位小时
      enableAfterOverTimeRemind: false, //是否启用超时后提醒：false-不启用，true-启用
      enableBeforeOverTimeRemind: false, //是否启用超时前提醒：false-不启用，true-启用
      enabled: false, //是否开启节点时效：false-不开启，true-开启
      id: null,
      slaAfterOverTimeRemindEmpIds: [], //超时后提醒指定人员ID对象
      slaBeforeOverTimeRemindEmpIds: [], //超时前提醒指定人员ID对象
      type: null, //触发条件类型
      customersData: [],
    })
    getworkTeamPageSelect('', slaData.value.slaConditionVos.length - 1)
  }

  //删除
  const detelePro = (index) => {
    if (slaData.value.slaConditionVos.length == 1) {
      ElMessage.warning('至少保留一条')
      return
    }
    slaData.value.slaConditionVos.splice(index, 1)
  }
  // 保存
  const onSave = async () => {
    if (!ruleFormRef.value) return
    await ruleFormRef.value?.validate(async (valid) => {
      if (valid) {
        let isTrue = slaData.value.slaConditionVos.every((o) => {
          return (
            o.ageingTime >= o.afterOverTimeRemindTime && o.ageingTime >= o.beforeOverTimeRemindTime
          )
        })
        if (!isTrue) {
          ElMessage({
            showClose: true,
            message: '提醒时间不能大于节点时效',
            duration: 4000,
            type: 'warning',
          })
        } else {
          loading.value = true
          await SaveSLA(slaData.value).then((res) => {
            if (res) {
              if (res.data.isError)
                ElMessage({
                  showClose: true,
                  message: res.data.message,
                  duration: 4000,
                  type: res.data.success ? 'success' : 'error',
                })
              if (res.data.success) {
                ruleFormRef.value.resetFields()
                TagsViewStore.delView(route.path)
                router.push({ path: '/busic/base/orderset', query: { active: 'OrderSLA' } })
              }
            }
          })
          loading.value = false
        }
      }
    })
  }
  // 取消
  const onCancel = () => {
    if (!ruleFormRef.value) return
    ruleFormRef.value.resetFields()
    TagsViewStore.delView(route.path)
    router.push({ path: '/busic/base/orderset', query: { active: 'OrderSLA' } })
  }
</script>
<style lang="scss" scoped>
  @import './index';

  :deep(.el-input .el-input__wrapper) {
    height: auto !important;
  }
</style>
